// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html


const {ccclass, property, requireComponent, executeInEditMode} = cc._decorator;



@ccclass
// @requireComponent(cc.Sprite)
@executeInEditMode
export default class SimPostProcessing extends cc.Component {

    @property(cc.Camera)
    camera:cc.Camera = null;

    @property(cc.Sprite)
    sprite:cc.Sprite = null;

    private _renderTexture:cc.RenderTexture = new cc.RenderTexture();


    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this._renderTexture.initWithSize(this.node.width, this.node.height, 36168/*gl.STENCIL_INDEX8*/);

        if(this.sprite) {
            let sf = new cc.SpriteFrame(this._renderTexture);
            sf.setFlipY(true);
            this.sprite.spriteFrame = sf;
        }

        let camera = this.camera;
        if(camera) {
            camera.targetTexture = this._renderTexture;
            camera.enabled = false;
        }

        this.node.on(cc.Node.EventType.SIZE_CHANGED, this.onSizedChanged, this);
        cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.onBeforeDraw, this);
    }

    private onSizedChanged() {
        this._renderTexture.initWithSize(this.node.width, this.node.height, 36168/*gl.STENCIL_INDEX8*/);
        this.camera && (this.camera.targetTexture = this._renderTexture);
    }

    private onBeforeDraw() {
        let camera = this.camera;
        if(!camera) return;

        camera.enabled = true;
        camera.render();
        camera.enabled = false;
    }
}
